<template>
  <div class="list-container">
    <div class="search-wrap clearfix">
      <div class="search-wrap-conditions fl">
        <el-select
          v-model="listQuery.condition.categoryCode"
          clearable
          placeholder="请选择位置"
          @change="resetPage"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </div>

      <div class="search-wrap-btn fr">
        <el-button :disabled="loading" type="primary" @click="resetPage">搜索</el-button>
        <el-button :disabled="loading" type="success" @click="add">添加</el-button>
      </div>
    </div>
    <div class="main-wrapper">
      <custom-table :data="listData" :columns="columns">
        <template slot-scope="{ row }">
          <el-button type="text" @click="revise(row)">修改</el-button>
          <el-button type="text" @click="delect(row)">删除</el-button>
        </template>
      </custom-table>
      <pagination :total="total" :page="listQuery.pager.page" @pagination="pagination" />
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <div class="matgin30">
        <el-form
          ref="dialogForm"
          :rules="rules"
          class="teaching-form"
          label-width="100px"
          :model="dialogList"
        >
          <el-form-item v-if="categoryList" prop="categoryCode" label="分类">
            <el-col :span="14">
              <el-select
                v-model="dialogList.categoryCode"
                style="width: 100%;"
                placeholder="请输入或选择标签"
              >
                <el-option
                  v-for="item in categoryList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-col>
          </el-form-item>

          <el-form-item label="封面图片：" prop="imgs">
            <el-col :span="14">
              <el-upload
                class="avatar-uploader"
                :action="action"
                :header="uploadHeader"
                :data="uploadForm"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload"
              >
                <div
                  class="uploader-text-box"
                  style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;"
                >
                  <img
                    v-if="dialogList.imgs"
                    :src="dialogList.imgs"
                    class="avatar"
                    style="width: 100%; height: 100%;"
                  />
                  <div v-else>
                    <i class="el-icon-plus avatar-uploader-icon uploader-icon" />
                    <div class="el-upload__text upload__text" style="font-size:16px;">上传图片</div>
                    <div class="el-upload__text upload__text" style="font-size:16px;">686*240</div>
                  </div>
                </div>
              </el-upload>
            </el-col>
          </el-form-item>

          <el-form-item label="备注">
            <el-col :span="14">
              <el-input v-model="dialogList.remark" placeholder="请输入备注" />
            </el-col>
          </el-form-item>

          <el-form-item label="跳转链接">
            <el-col :span="14">
              <el-input v-model="dialogList.url" placeholder="请输入跳转链接" />
            </el-col>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveBtn('dialogForm')">保存</el-button>
        <!-- <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveBtn">保存</el-button>-->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CustomTable from '@/components/CustomTable/index';
import Pagination from '@/components/Pagination/index';
import { preUpload } from '@/api/uploads';

import { optionsStatus } from './mock.js';
import {
  pageAdvertCategory,
  pageAdvert,
  updateAdvert,
  saveAdvert,
  deleteAdvert
} from '@/api/popularize';

export default {
  name: 'List',
  components: {
    CustomTable,
    Pagination
  },
  data () {
    return {
      disabled: false,
      action: 'https://yes910-pub.obs.cn-south-1.myhuaweicloud.com',
      uploadHeader: {
        'Content-Type': 'multipart/form-data'
      },
      uploadForm: {},

      loading: true,
      categoryList: null, // optionsStatus
      valueDate: '',
      categoryQuery: {
        condition: {
          condition: ''
        },
        pager: {
          page: 1,
          pageSize: 100
        }
      },
      listQuery: {
        condition: {
          categoryCode: '',
          name: ''
        },
        pager: {
          page: 1,
          pageSize: 10
        }
      },

      optionsStatus: optionsStatus,

      dialogTitle: '添加广告图片',
      dialogVisible: false,
      dialogList: {
        id: '',
        categoryCode: '', // 分类
        imgs: '', // 图片
        remark: '', // 备注
        url: '' // 跳转链接
      },
      rules: {
        categoryCode: [
          { required: true, message: '请选择分类!', trigger: 'change' }
        ],
        imgs: [
          { required: true, message: '请上传广告图片!', trigger: 'change' }
        ],
        remark: [{ required: true, message: '请输入备注!', trigger: 'blur' }],
        url: [{ required: true, message: '请输入跳转链接!', trigger: 'blur' }]
      },

      listData: [],
      total: 0,
      columns: [
        { label: '序号', value: 'index', width: '60px', align: 'center' },
        {
          label: '位置',
          value: 'categoryCodeTxt',
          width: '180px',
          align: 'center'
        },
        { label: '图片', value: 'imgs', align: 'center' },
        { label: '链接', value: 'url', width: '200px', align: 'center' },
        { label: '操作', value: 'todo', width: '100px', align: 'center' }
      ]
    };
  },
  created () {
    pageAdvertCategory(this.categoryQuery).then(res => {
      this.categoryList = res.data.records;
    });

    this.init();
  },
  methods: {
    resetPage () {
      this.listQuery.pager.page = 1;
      this.listQuery.pager.pageSize = 10;
      this.init();
    },
    uploadSuccess (res, file) {
      this.dialogList.imgs = this.coverImg;
    },
    beforeUpload (file) {
      const imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/;
      if (!imgStr.test(file.name)) {
        this.$message.error('上传格式不对，请重新上传!');
        return false;
      }
      let continueUpload = false;
      return new Promise((resolve, reject) => {
        preUpload({
          biz: 'OPEN',
          name: file.name,
          size: file.size
        })
          .then(res => {
            this.action = res.data.action;
            this.uploadForm = res.data.parameters;
            continueUpload = true;
            this.coverImg = res.data.uri;
            resolve(continueUpload);
          })
          .catch(err => {
            reject(continueUpload);
          });
      });
    },

    // 弹窗关闭按钮
    handleClose (done) {
      done();
    },
    init () {
      this.loading = true;
      pageAdvert(this.listQuery)
        .then(res => {
          this.categoryList.map(item => {
            if (this.checkArr(res.data.records)) {
              res.data.records.map(records => {
                console.log('item.code:', records.categoryCode, item.code);
                if (records.categoryCode === item.code) {
                  records.categoryCodeTxt = item.name;
                }
              });
            }
          });
          this.listData = res.data.records;
          console.log('this.listData:', this.listData);
          this.total = res.data.total;
          this.loading = false;
        })
        .catch(error => {
          this.loading = false;
        });
    },
    add () {
      this.dialogList = {
        id: '',
        categoryCode: '', // 分类
        imgs: '', // 图片
        remark: '', // 备注
        url: '' // 跳转链接
      };
      this.dialogVisible = true;
    },
    delect (item) {
      var msg = '确认是否删除该广告图！';
      this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteAdvert({
            id: item.id
          })
            .then(res => {
              this.init();
            })
            .catch(error => {
              this.loading = false;
            });
        })
        .catch(() => {
          // 取消操作
          console.log('cancel');
        });
    },
    revise (item) {
      console.log('item:', item);
      // this.dialogList.id = id;
      this.dialogList = {
        id: item.id,
        categoryCode: item.categoryCode, // 分类
        imgs: item.imgs, // 图片
        remark: item.remark, // 备注
        url: item.url // 跳转链接
      };
      this.dialogVisible = true;
    },
    saveBtn (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log('submit!');

          var data = {
            id: this.dialogList.id ? this.dialogList.id : '',
            categoryCode: this.dialogList.categoryCode
              ? this.dialogList.categoryCode
              : '',
            imgs: this.dialogList.imgs ? this.dialogList.imgs : '',
            remark: this.dialogList.remark ? this.dialogList.remark : '',
            url: this.dialogList.url ? this.dialogList.url : ''
          };

          if (this.dialogList.id) {
            updateAdvert(data).then(res => {
              console.log('修改:', res.data);
              this.init();
              this.dialogVisible = false;
            });
          } else {
            saveAdvert(data).then(res => {
              this.listQuery = {
                condition: {
                  categoryCode: '',
                  name: ''
                },
                pager: {
                  page: 1,
                  pageSize: 10
                }
              };
              this.init();
              this.dialogVisible = false;
            });
          }

          console.log(this.dialogList);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      // this.dialogVisible = false;
    },

    pagination ({ page, limit }) {
      this.listQuery.pager.page = page;
      this.listQuery.pager.pageSize = limit;
      console.log(this.listQuery);
      this.init();
    },
    getDetail (id) {
      console.log(id);
      this.$router.push({
        path: `/content/teachingDetail`,
        query: { param: id }
      });
    }
  }
};
</script>

<style lang="scss" scoped></style>
